package ejb;

import entities.Clients;
import java.util.*;
import javax.ejb.Stateless;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author CDI215
 */
@Stateless
public class GererConnect implements GererConnectLocal {

    @PersistenceContext(unitName = "LibWebEjb-ejbPU")
    private EntityManager em;
    private static final String CHAMP_LOGIN = "email";
    private static final String CHAMP_MDP = "mdp";
    private Map<String, String> erreurs = new HashMap<String, String>();
    private String resultat;
    private ArrayList<Clients> liste;

    public GererConnect() {
    }

    @Override
    public Clients connect(HttpServletRequest request) {
        Clients client = null;
        String login = getValeurChamp(request, CHAMP_LOGIN);
        String mdp = getValeurChamp(request, CHAMP_MDP);

        Query qry = em.createQuery("SELECT c FROM Clients c WHERE c.login = ?1 AND c.actif = true");
        try {
            client = (Clients) qry.setParameter(1, login).getSingleResult();
            if (client != null) {
                if (!mdp.equals(client.getMdp())) {
                    setErreur(CHAMP_LOGIN, null);
                    setErreur(CHAMP_MDP, "Erreur de mot de passe !");
                }else{
                    raz();
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            setErreur(CHAMP_LOGIN, "Profil inexistant !");
        }
        return client;
    }

    @Override
    public Clients autoConnect(Long clientId) {
    Clients client = null;
        try {
            client = em.find(Clients.class, clientId);
            
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } 
        return client;
    }

    @Override
    public Map<String, String> getErreurs() {
        return erreurs;
    }

    /*
     * Ajoute un message correspondant au champ spécifié à la map des erreurs.
     */
    private void setErreur(String champ, String message) {
        erreurs.put(champ, message);
    }
    
    /*
     * Réinitialise la map des erreurs.
     */
    private void raz() {
        erreurs.clear();
    }

    /*
     * Méthode utilitaire de nettoyage qui retourne null si un champ est vide, et son contenu
     * sinon.
     */
    private static String getValeurChamp(HttpServletRequest request, String nomChamp) {
        String valeur = request.getParameter(nomChamp);
        if (valeur == null || valeur.trim().length() == 0) {
            return null;
        } else {
            return valeur;
        }
    }
}